import time
import cv2
import numpy as np
import Processor.Converter as Converter

from PyQt5.QtWidgets import QDialog
from Plugin.specular.specular_design import Ui_SpecularController


class SpecularController(QDialog, Ui_SpecularController):
    layer = None  # 图层
    mat = None  # 原始Mat 数据

    def __init__(self, parent, mat=None):
        super().__init__(parent)
        self.setupUi(self)
        self.__initUI(parent)
        self.mat = mat

    def reject(self):
        """
        取消操作
        :return:
        """
        image = Converter.Numpy2QImage(self.mat)
        self.layer.updatePixmap(image)
        QDialog.reject(self)

    def __initUI(self, parent):
        self.setWindowTitle('图像修复')
        # 定位
        self.resize(325, 200)
        pos = parent.geometry()
        self.move((pos.width() - self.width()) / 2, (pos.height() - self.height()) / 2)
        # 信号
        #       对话框确定
        self.DialogButtonBox.accepted.connect(self.accept)
        self.DialogButtonBox.rejected.connect(self.reject)

    def updateSlot(self):
        gradientWidget = self.gradientWidget
        color1 = gradientWidget.getColor(0)
        color2 = gradientWidget.getColor(1)
        self.blur(color1, color2)

    def blur(self, color1, color2):
        """
        :param color1:
        :param color2:
        :return:
        """
        start = time.perf_counter()
        mat = self.mat.copy()
        color1 = [color1.red(), color1.green(), color1.blue()]
        color2 = [color2.red(), color2.green(), color2.blue()]
        for i in range(0, 3):
            if color1[i] > color2[i]:
                color1[i] = color2[i]
        data = mat[..., 0:3]
        # 图片二值化处理，把[240, 240, 240]~[255, 255, 255]以外的颜色变成0
        thresh = cv2.inRange(data, np.array(color1), np.array(color2))

        # 创建形状和尺寸的结构元素
        kernel = np.ones((3, 3), np.uint8)
        # 扩张待修复区域
        hi_mask = cv2.dilate(thresh, kernel, iterations=1)
        specular = cv2.inpaint(data, hi_mask, 5, flags=cv2.INPAINT_TELEA)
        mat[..., 0:3] = specular
        image = Converter.Numpy2QImage(mat)
        end = time.perf_counter()
        print('Specular', '耗时：', end - start)
        self.layer.updatePixmap(image)


Window = None  # 主窗体


def newSpecular():
    """
    :param window: 主窗体
    :return:
    """
    window = Window
    layer = window.currentLayer
    if layer:
        image = layer.image  # 当前图层QImage句柄
        mat = Converter.QImage2Numpy(image)
        controller = SpecularController(window, mat)
        controller.layer = layer
        if controller.exec_():
            del controller
            pass


def init(window):
    """
    初始化
    :param window: 主窗体
    :return:
    """
    global Window
    Window = window
    __menu()  # 创建菜单栏


def __menu():
    """
    将插件入口连接到菜单栏，这样，点击菜单栏按钮时，能使用本插件功能
    :return:
    """
    window = Window
    menuBar = window.menuBar()  # 菜单栏句柄
    menu_filter = menuBar.menu_filter  # 滤波栏句柄
    action = menuBar.newAction('图像修复', menuBar)  # 新建菜单栏选项
    action.func = newSpecular  # 当按钮出发时，运行 newBlur 方法
    menu_filter.addAction(action)  # 把选项添加到 滤波 分类
